'''
Created on 2011-12-10

@author: jiangxd
'''
from Tkinter import *
from ttk import *
import os.path
import codecs
from dict import baidu
import db

class DictView:
		
	def __init__(self, master):
		pass
	
	def init_widgets(self, frame):
		frame.bind("<FocusIn>", self.on_focus)
		self.bar = Frame(frame,name="dict-bar")
		self.bar.pack(side=TOP)

		self.word = Entry(self.bar, name="dict-word",width=32)
		self.word.bind("<Return>", self.on_lookup)
		self.word.bind("<FocusIn>", self.on_focus_word)
		self.word.pack(side=LEFT)
		self.word.focus_set()

		self.lookup_btn = Button(self.bar,text="Lookup",command=self.on_lookup)
		self.lookup_btn.pack(side=LEFT)

		self.realword_var = StringVar(frame)
		self.realword = Label(frame,name="dict-realword",foreground="#000000",font=("Helvetica", 20),textvariable=self.realword_var)
		self.realword.pack(side=TOP)
		
		self.phonetic_var = StringVar(frame)
		self.phonetic = Label(frame,name="dict-phonetic",foreground="#AAAA88",font=("Helvetica", 16),textvariable=self.phonetic_var)
		self.phonetic.pack(side=TOP)

		self.scroll_frame = Frame(frame,name='dict-scroll')
		self.scroll_frame.pack(side=TOP)
		
		self.explain = Text(self.scroll_frame,name="dict-explain",height=31,state=DISABLED)
		self.explain.pack(side=LEFT)

		self.scroll = Scrollbar(self.scroll_frame)
		self.scroll.pack(side=RIGHT,fill=Y)
		self.explain.config(yscrollcommand=self.scroll.set)
		self.scroll.config(command=self.explain.yview)
		
	def on_lookup(self,*args):
		self.explain.config(state=NORMAL)
		word=self.word.get()
		wordobj = db.get_word(word)
		if wordobj != None:
			realword = word
			explain = wordobj['explain']
			phonetic= wordobj['phonetic']
			db.update_dictated_status(wordobj)
		else:
			explain, phonetic, realword = baidu.lookup(word)
			if explain != None and len(explain.strip()) > 0:
				db.add_word(realword, explain, phonetic)
		self.phonetic_var.set(phonetic)
		self.realword_var.set(realword)
		self.explain.delete(1.0,END)
		self.explain.insert(1.0,explain)
		self.explain.config(state=DISABLED)
	
	def on_focus_word(self,event,*args):
		self.word.select_range(0, END)

	def on_focus(self,event,*args):
		self.word.focus_set()
		
